#include "ADuCM4050.h"
#include <stdio.h>
#include <stdint.h>
#include <drivers/uart/adi_uart.h>
#include "GPIO.h"
#include "DELAY.h"

/* Amount of memory required by the driver for Rx and TX only. */
#define ADI_UART_MEMORY_SIZE  (ADI_UART_BIDIR_MEMORY_SIZE)

#define UART_DEVICE_NUM 0

/* Handle for the UART device */
ADI_UART_HANDLE handle_UART0;

/* Memory for the driver */
uint8_t UartDeviceMem[ADI_UART_MEMORY_SIZE];


//串口打印预设
#pragma import(__use_no_semihosting_swi)
struct __FILE { int handle; /* Add whatever you need here */ };
FILE __stdout;
FILE __stdin;
void _sys_exit(int x) 
{ 
    x = x; 
} 
void _ttywrch(int ch)
{
    ch = ch;
}
//串口打印配置函数
int fputc(int ch, FILE *f)  
{
 uint32_t usart0_error;
 adi_uart_Write(handle_UART0,&ch,1,false,&usart0_error);
 
 return ch;
}

uint8_t dat;
void callback_UART0(void	*pCBParam,uint32_t	Event,void	*pArg);
void init_UART(void)
{	
	uint32_t gpio0_cfg = *pREG_GPIO0_CFG;
	gpio0_cfg &= ~(BITM_GPIO_CFG_PIN10 | BITM_GPIO_CFG_PIN11);
	gpio0_cfg |= (1u << BITP_GPIO_CFG_PIN10) | (1u << BITP_GPIO_CFG_PIN11);
	*pREG_GPIO0_CFG = gpio0_cfg;
	
	adi_uart_Open(0,ADI_UART_DIR_BIDIRECTION,&UartDeviceMem,ADI_UART_BIDIR_MEMORY_SIZE,&handle_UART0);
	
	
	uint32_t pAutobaudErrors_UART0;
	
	adi_uart_SetRxFifoTriggerLevel(handle_UART0,ADI_UART_RX_FIFO_TRIG_LEVEL_1BYTE);
	adi_uart_EnableFifo(handle_UART0,true);
	
	adi_uart_SetConfiguration(handle_UART0,ADI_UART_NO_PARITY,ADI_UART_ONE_STOPBIT,ADI_UART_WORDLEN_8BITS);  //0校验 1停止 8带宽
	
//	adi_uart_FlushTxFifo(handle_UART0);
//	adi_uart_FlushRxFifo(handle_UART0);
	adi_uart_ConfigBaudRate(handle_UART0,4,1,1563,3);
	
	adi_uart_RegisterCallback(handle_UART0,callback_UART0,NULL);
	
	uint16_t pBuffer_TX=0xff;  //发送
//	uint16_t pBuffer_RX;  //接收
	adi_uart_Write(handle_UART0,&pBuffer_TX,1,false,&pAutobaudErrors_UART0);  //阻塞发送
//	adi_uart_SubmitRxBuffer(handle_UART0,&pBuffer_RX,1,true);  //非阻塞接收
	
}

void init_PWR(void)
{
	adi_pwr_Init();
	adi_pwr_SetClockDivider(ADI_CLOCK_HCLK,1);
	adi_pwr_SetClockDivider(ADI_CLOCK_PCLK,1);
}

int main(void)
{
	init_PWR();
	init_UART();
	while(1){
		printf("%x\n",dat);
		delay_ms(100);
	}
}
void callback_UART0(void	*pCBParam,uint32_t	Event,void	*pArg)
{
//	adi_uart_FlushRxChannel(handle_UART0);	
	uint8_t RX;
	adi_uart_GetRX(handle_UART0,&RX);
	dat=RX;

}
